package cn.yuan.arithmetic.sort;

/**
 * 二分插入排序实现.
 *
 * @author : yjs
 * @date: 2020-12-17 10:39
 */
public class DichotomySort {
    public static void main(String[] args) {
        int[] array = {3,4,7,4,1,9,13,24,11,45,22,45};
        System.out.println(print(array));
        DichotomySort.sort(array);
        System.out.println(print(array));
    }
    /**
     * 实现
     */
    public static void sort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int temp = array[i];
            int left = 0;
            int right = i - 1;
            int mid = 0;
            while (left <= right) {
                mid = (left + right) / 2;
                if (temp < array[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            for (int j = i - 1; j >= left; j--) {
                array[j + 1] = array[j];
            }
            if (left != i) {
                array[left] = temp;
            }
        }
    }

    /**
     * 打印
     */
    private static String print(int[] array) {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
            if (i < array.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
